package com.smart.auth.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smart.auth.mapper.*;
import com.smart.auth.service.UserService;
import com.smart.common.bean.entity.*;
import com.smart.common.constant.AuthConstants;
import com.smart.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yangbingquan
 * @version 1.0
 * @date 2021/5/12 16:50
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;

    @Resource
    UserRoleMapper UserRoleMapper;

    @Resource
    RedisService redisService;

    @Resource
    PermissionMapper permissionMapper;
    @Resource
    RolePermissionMapper rolePermissionMapper;

    @Override
    public User getUserByUsername(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        if (user == null) {
            return null;
        }
        List<UserRole> userRoles = UserRoleMapper.selectList(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, user.getId()));
        List<Long> roleIdList = userRoles.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
        user.setRoleIds(roleIdList);
        return user;
    }

    @Override
    public void savePermission() {
        Map<String, String> map = new HashMap<>();
        List<Permission> permissions = permissionMapper.selectList(new QueryWrapper<Permission>());
        permissions.forEach(p -> {
            String permission = p.getPerm();
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(new QueryWrapper<RolePermission>().lambda().eq(RolePermission::getPermissionId, p.getId()));
            List<String> collect = rolePermissions.stream().map(item -> AuthConstants.AUTHORITY_PREFIX + item.getRoleId()).collect(Collectors.toList());
            TreeSet<String> roleSet = new TreeSet<>(collect);
            map.put(permission, JSON.toJSONString(roleSet));
        });
        redisService.hPutAll(AuthConstants.PERMISSION_ROLES_KEY, map);
    }

    @Override
    public Set<String> getPermission() {
        Map<String, Object> permissionRoles = redisService.hGetAll(AuthConstants.PERMISSION_ROLES_KEY);
        Iterator<String> iterator = permissionRoles.keySet().iterator();
        // 请求路径匹配到的资源需要的角色权限集合authorities统计
        Set<String> authorities = new HashSet<>();
        while (iterator.hasNext()) {
            String pattern = iterator.next();
            authorities.addAll(Convert.toList(String.class, permissionRoles.get(pattern)));
        }
        log.info("{}", authorities);
        return authorities;
    }
}
